package com.uddenberg.wt;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Locale;

import com.uddenberg.wt.dbdefinitions.GeneralDataDefinition.GeneralDataColumns;
import com.uddenberg.wt.helpers.GeneralHelper;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class InsertGeneralActivity extends Activity {
	
	private static final String TAG = "InsertGeneralActivity";
	
	private Button btnFood;
	private Button btnDaily;
	private Button btnSave;
	
	// All questions
	private static TextView txtDate;
	private static TextView txtTime;
	private RatingBar rbWellness;
	private RatingBar rbStress;
	private RatingBar rbEnergy;
	private RatingBar rbHappiness;
	private Spinner spActivity;
	private int spActivityValue = 1;
	private RatingBar rbFocus;
	private RatingBar rbValue;
	
	private static int mHour;
    private static int mMinute;
    private static int mYear;
    private static int mMonth;
    private static int mDay;
    
    
    static final int TIME_DIALOG_ID = 0;
    static final int DATE_DIALOG_ID = 1;
    
    private Uri mUri;
    
    private static final String[] PROJECTION = new String[] {
    	GeneralDataColumns._ID, // 0
    	GeneralDataColumns.WELLNESS, // 1
    };
    
    
    // the callback received when the user "sets" the time in the dialog
    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                mHour = hourOfDay;
                mMinute = minute;
                updateTime();
            }
        };
	
     // the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDate();
                }
            };
        
            
     
            
            
            
            
	/** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        
        View viewToLoad = LayoutInflater.from(this.getParent()).inflate(R.layout.insertgeneral_header, null);
        this.setContentView(viewToLoad);  

        
        // If no data was given in the intent (because we were started
        // as a MAIN activity), then use our default content provider.
        Intent intent = getIntent();
        if (intent.getData() == null) {
            intent.setData(GeneralDataColumns.CONTENT_URI);
        }
        
        mUri = intent.getData();
        
        // Perform a managed query. The Activity will handle closing and requerying the cursor
        // when needed.
        @SuppressWarnings("unused")
		Cursor cursor = managedQuery(getIntent().getData(), PROJECTION, null, null,
        		GeneralDataColumns.DEFAULT_SORT_ORDER);
        
        
        // Handle the date and time view
        txtDate = (TextView)findViewById(R.id.general_txt_date);
        txtTime = (TextView)findViewById(R.id.general_txt_time);
        
        // get the current time
        final Calendar c = Calendar.getInstance();
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        
        updateTime();
        updateDate();
        
        // Add a click listener to the time and date textview
        txtDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(!isFinishing()) {
					showDialog(DATE_DIALOG_ID);
				}
			}
        });
        txtTime.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(!isFinishing()) {
					showDialog(TIME_DIALOG_ID);
				}
			}
        });
        
        
        spActivity = (Spinner) findViewById(R.id.general_spinner_activity);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
        		this.getParent(), R.array.activity_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spActivity.setAdapter(adapter);
        
        spActivity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                Object item = parent.getItemAtPosition(pos);
                
                if (String.valueOf(item).equals("Work activity")) {
                	spActivityValue = 1;
                } else if (String.valueOf(item).equals("Social activity")) {
                	spActivityValue = 2;
                } else if (String.valueOf(item).equals("Personal activity")) {
                	spActivityValue = 3;
                } else if (String.valueOf(item).equals("School activity")) {
                	spActivityValue = 4;
                }
                
            }
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        
        
        btnFood = (Button)findViewById(R.id.general_food_insert_button);
        btnFood.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				
				final Intent foodIntent = new Intent(v.getContext(), InsertFoodGroupActivity.class);
				
				// Create the view using InsertGroup's LocalActivityManager  
		        View view = InsertGroupActivity.group.getLocalActivityManager()  
			        .startActivity("InsertFoodGroupActivity", foodIntent  
			        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))  
			        .getDecorView();  
		  
		        // Again, replace the view  
		        InsertGroupActivity.group.replaceView(view);  
			}
		});
        
        
        btnDaily = (Button)findViewById(R.id.general_daily_insert_button);
        btnDaily.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				final Intent dailyIntent = new Intent(v.getContext(),InsertDailyActivity.class);
		        View view = InsertGroupActivity.group.getLocalActivityManager()
		        		.startActivity("InsertDailyActivity", dailyIntent
		        		.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))  
		                .getDecorView();  

		        // Again, replace the view  
		        InsertGroupActivity.group.replaceView(view); 
			}
		});
        
        
        btnSave = (Button)findViewById(R.id.general_save);
        btnSave.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ContentValues values = new ContentValues();
				
				
				final Calendar cal = Calendar.getInstance();
		    	cal.set(Calendar.MONTH, mMonth);
		    	cal.set(Calendar.DAY_OF_MONTH, mDay);
		    	cal.set(Calendar.YEAR, mYear);
		    	cal.set(Calendar.HOUR_OF_DAY, mHour);
		    	cal.set(Calendar.MINUTE, mMinute);
				values.put(GeneralDataColumns.TIME, cal.getTimeInMillis()/1000);
				cal.clear();
				
				rbWellness = (RatingBar)findViewById(R.id.general_ratbar_wellness);
				values.put(GeneralDataColumns.WELLNESS, rbWellness.getRating());
				
				rbStress = (RatingBar)findViewById(R.id.general_ratbar_stress);
				values.put(GeneralDataColumns.STRESS, rbStress.getRating());
				
				rbEnergy = (RatingBar)findViewById(R.id.general_ratbar_energy);
				values.put(GeneralDataColumns.ENERGY, rbEnergy.getRating());
				
				rbHappiness = (RatingBar)findViewById(R.id.general_ratbar_happiness);
				values.put(GeneralDataColumns.HAPPINESS, rbHappiness.getRating());
				
				rbFocus = (RatingBar)findViewById(R.id.general_ratbar_focus);
				values.put(GeneralDataColumns.FOCUS, rbFocus.getRating());
				
				rbValue = (RatingBar)findViewById(R.id.general_ratbar_value);
				values.put(GeneralDataColumns.VALUE, rbValue.getRating());
				
				// And the activity
				values.put(GeneralDataColumns.ACTIVITY, spActivityValue);
				
				CharSequence text;
				
				if(rbWellness.getRating() > 0) {
					Uri newUri = null;
					try {
						newUri = getContentResolver().insert(mUri, values);
		            } catch (Exception e) {
		            	Log.e(TAG, e.getMessage());
		            } 
		            
					if(newUri == null) {
						text = "Unable to save post";
					} else {
						text = "Saved!";
						Log.w("URI: ", newUri.toString());
						// Reset all Ratbars and dates
						rbWellness.setRating(0);
						rbStress.setRating(0);
						rbEnergy.setRating(0);
						rbHappiness.setRating(0);
						rbFocus.setRating(0);
						rbValue.setRating(0);
						spActivityValue = 1;
						spActivity.setSelection(1);
						
						mYear = c.get(Calendar.YEAR);
						mMonth = c.get(Calendar.MONTH);
						mDay = c.get(Calendar.DAY_OF_MONTH);
						mHour = c.get(Calendar.HOUR_OF_DAY);
						mMinute = c.get(Calendar.MINUTE);
						
						updateTime();
						updateDate();
						
					}
				} else {
					text = "You must select your current wellness";
				}
	            Context context = getApplicationContext();
	            int duration = Toast.LENGTH_LONG;

	            Toast toast = Toast.makeText(context, text, duration);
	            toast.show();
			}
		});
        
    }

    private static void updateTime() {
    	txtTime.setText(
	        new StringBuilder()
                .append(GeneralHelper.pad(mHour)).append(":")
                .append(GeneralHelper.pad(mMinute)));
    }
    
    private static void updateDate() {
    	final Calendar cal = Calendar.getInstance();
    	cal.set(Calendar.MONTH, mMonth);
    	cal.set(Calendar.DAY_OF_MONTH, mDay);
    	cal.set(Calendar.YEAR, mYear);
    	
    	 
    	String text = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault())
    			.format(cal.getTime());
    	txtDate.setText(text);
    }
    
    
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case TIME_DIALOG_ID:
            return new TimePickerDialog(InsertGroupActivity.group,
                    mTimeSetListener, mHour, mMinute, true);
            
        case DATE_DIALOG_ID:
            return new DatePickerDialog(InsertGroupActivity.group,
                        mDateSetListener,
                        mYear, mMonth, mDay);
        }
        
        return null;
    }
    
    
}
